package com.zkool.mysite.common.db;

import java.io.IOException;

import org.apache.log4j.Logger;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.dialect.OracleDialect;
import com.jfinal.plugin.activerecord.dialect.PostgreSqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.zkool.mysite.common.DictKeys;

/**
 * 独立启动Jfinal中的插件，不依赖web容器调用插件
 * @author Administrator
 *
 */
public class ConfigCore {

	private static Logger log = Logger.getLogger(ConfigCore.class);
	
    public ConfigCore() throws IOException {
    	PropKit.use("mysite.properties");
    	//初始化多数据源
    	String dataSourceStr = PropKit.get(DictKeys.db_dataSource);
    	String[] dataSources = dataSourceStr.split(",");
    	log.info("开始初始化数据源,总共有"+dataSources.length+"个数据源");
		for(String dataSource:dataSources){
			log.info("configPlugin 配置Druid数据库连接池连接属性");
			DruidPlugin druidPlugin = new DruidPlugin(PropKit.get(dataSource+"."+DictKeys.db_connection_jdbcUrl), 
					PropKit.get(dataSource+"."+DictKeys.db_connection_userName), 
					PropKit.get(dataSource+"."+DictKeys.db_connection_passWord).trim(),
					PropKit.get(dataSource+"."+DictKeys.db_connection_driverClass));
			
			log.info("configPlugin 配置Druid数据库连接池大小");
			druidPlugin.set(
					PropKit.getInt(DictKeys.db_initialSize), 
					PropKit.getInt(DictKeys.db_minIdle), 
					PropKit.getInt(DictKeys.db_maxActive));
			ActiveRecordPlugin arp = new ActiveRecordPlugin(dataSource, druidPlugin);
			boolean devMode = Boolean.parseBoolean(PropKit.get(DictKeys.config_devMode));
			arp.setDevMode(devMode); // 设置开发模式
			arp.setShowSql(devMode); // 是否显示SQL
			arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));// 大小写不敏感
			
			log.info("configPlugin 数据库类型判断");
			String db_type = PropKit.get(dataSource+"."+DictKeys.db_type_key);
			if(db_type.equals(DictKeys.db_type_postgresql)){
				log.info("configPlugin 使用数据库类型是 postgresql");
				arp.setDialect(new PostgreSqlDialect());
				
			}else if(db_type.equals(DictKeys.db_type_mysql)){
				log.info("configPlugin 使用数据库类型是 mysql");
				arp.setDialect(new MysqlDialect());
				
			}else if(db_type.equals(DictKeys.db_type_oracle)){
				log.info("configPlugin 使用数据库类型是 oracle");
				druidPlugin.setValidationQuery("select 1 FROM DUAL"); //指定连接验证语句
				arp.setDialect(new OracleDialect());
			}
			
//			arp.addMapping(tableName, modelClass);
			
			druidPlugin.start();
			arp.start();
		}
    }
    
}
